<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 聊天演示</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .chat-container {
            width: 90%;
            max-width: 800px;
            height: 80vh;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .chat-header {
            background: #4a90e2;
            color: white;
            padding: 20px;
            text-align: center;
            font-size: 1.2em;
            font-weight: bold;
        }
        
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8f9fa;
        }
        
        .message {
            margin-bottom: 15px;
            display: flex;
            align-items: flex-start;
        }
        
        .message.user {
            justify-content: flex-end;
        }
        
        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            word-wrap: break-word;
        }
        
        .message.user .message-content {
            background: #4a90e2;
            color: white;
            margin-left: 20px;
        }
        
        .message.ai .message-content {
            background: white;
            color: #333;
            border: 1px solid #e1e8ed;
            margin-right: 20px;
        }
        
        .message-info {
            font-size: 0.8em;
            color: #666;
            margin-top: 5px;
        }
        
        .chat-input {
            padding: 20px;
            background: white;
            border-top: 1px solid #e1e8ed;
            display: flex;
            gap: 10px;
        }
        
        .input-field {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 25px;
            outline: none;
            font-size: 14px;
        }
        
        .input-field:focus {
            border-color: #4a90e2;
        }
        
        .send-button {
            padding: 12px 24px;
            background: #4a90e2;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s;
        }
        
        .send-button:hover {
            background: #357abd;
        }
        
        .send-button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 10px;
            color: #666;
        }
        
        .error {
            color: #e74c3c;
            background: #fdf2f2;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        
        .conversation-info {
            font-size: 0.9em;
            color: #666;
            padding: 10px 20px;
            background: #f0f0f0;
            border-bottom: 1px solid #ddd;
        }
        
        .mode-toggle {
            padding: 10px 20px;
            background: #f8f9fa;
            border-bottom: 1px solid #ddd;
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .mode-btn {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background: white;
            color: #666;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 14px;
        }
        
        .mode-btn:hover {
            background: #f0f0f0;
        }
        
        .mode-btn.active {
            background: #4a90e2;
            color: white;
            border-color: #4a90e2;
        }
        
        .streaming-indicator {
            display: none;
            color: #4a90e2;
            font-size: 0.9em;
            animation: pulse 1.5s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            🤖 AI 聊天助手 - Dify 集成演示
        </div>
        
        <div class="conversation-info">
            <span id="conversationId">会话ID: 未开始</span>
            <span style="float: right;">状态: <span id="status">就绪</span></span>
        </div>
        
        <div class="mode-toggle">
            <span>响应模式:</span>
            <button class="mode-btn active" id="syncBtn" onclick="setMode('sync')">同步</button>
            <button class="mode-btn" id="asyncBtn" onclick="setMode('async')">异步</button>
            <button class="mode-btn" id="streamBtn" onclick="setMode('stream')">流式</button>
            <div class="streaming-indicator" id="streamingIndicator">🔄 处理中...</div>
        </div>
        
        <div class="chat-messages" id="chatMessages">
            <div class="message ai">
                <div class="message-content">
                    👋 你好！我是 AI 助手，由 Dify 提供支持。有什么可以帮助你的吗？
                    <div class="message-info">系统消息</div>
                </div>
            </div>
        </div>
        
        <div class="loading" id="loading">
            🤔 AI 思考中...
        </div>
        
        <div class="chat-input">
            <input type="text" class="input-field" id="messageInput" placeholder="输入你的消息..." maxlength="500">
            <button class="send-button" id="sendButton" onclick="sendMessage()">发送</button>
        </div>
    </div>

    <script>
        let conversationId = null;
        let currentMode = 'sync';
        let currentEventSource = null;
        const apiBase = '/euc/api/chat';
        
        // 监听回车键
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message) return;
            
            addMessage(message, 'user');
            input.value = '';
            
            switch (currentMode) {
                case 'sync':
                    await sendSyncMessage(message);
                    break;
                case 'async':
                    await sendAsyncMessage(message);
                    break;
                case 'stream':
                    await sendStreamMessage(message);
                    break;
            }
        }
        
        async function sendSyncMessage(message) {
            setLoading(true);
            updateStatus('发送中...');
            
            try {
                const response = await fetch(apiBase + '/message', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        conversationId: conversationId,
                        userId: 'demo-user'
                    })
                });
                
                const result = await response.json();
                
                if (result.success && result.data) {
                    const aiResponse = result.data;
                    addMessage(aiResponse.answer, 'ai', aiResponse);
                    
                    if (aiResponse.conversationId) {
                        conversationId = aiResponse.conversationId;
                        updateConversationId(conversationId);
                    }
                    
                    updateStatus('就绪');
                } else {
                    addErrorMessage(result.message || '请求失败');
                    updateStatus('错误');
                }
            } catch (error) {
                console.error('发送消息失败:', error);
                addErrorMessage('网络错误，请检查连接');
                updateStatus('网络错误');
            } finally {
                setLoading(false);
            }
        }
        
        async function sendAsyncMessage(message) {
            setLoading(true);
            updateStatus('异步处理中...');
            
            try {
                const response = await fetch(apiBase + '/message/async', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        conversationId: conversationId,
                        userId: 'demo-user'
                    })
                });
                
                const result = await response.json();
                
                if (result.success && result.data) {
                    const aiResponse = result.data;
                    addMessage(aiResponse.answer, 'ai', aiResponse);
                    
                    if (aiResponse.conversationId) {
                        conversationId = aiResponse.conversationId;
                        updateConversationId(conversationId);
                    }
                    
                    updateStatus('异步完成');
                } else {
                    addErrorMessage(result.message || '异步请求失败');
                    updateStatus('异步错误');
                }
            } catch (error) {
                console.error('异步消息发送失败:', error);
                addErrorMessage('异步网络错误，请检查连接');
                updateStatus('异步网络错误');
            } finally {
                setLoading(false);
            }
        }
        
        async function sendStreamMessage(message) {
            if (currentEventSource) {
                currentEventSource.close();
            }
            
            setLoading(true);
            updateStatus('流式响应中...');
            document.getElementById('streamingIndicator').style.display = 'block';
            
            const messageId = 'stream-' + Date.now();
            const messagesContainer = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ai';
            messageDiv.id = messageId;
            messageDiv.innerHTML = '<div class="message-content"><div class="stream-content"></div><div class="message-info">流式响应中...</div></div>';
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            
            try {
                const response = await fetch(apiBase + '/message/flux', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'text/event-stream',
                    },
                    body: JSON.stringify({
                        message: message,
                        conversationId: conversationId,
                        userId: 'demo-user'
                    })
                });
                
                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let fullResponse = '';
                
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    
                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop();
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6).trim();
                            if (data && data !== '[DONE]') {
                                try {
                                    const parsed = JSON.parse(data);
                                    if (parsed.event === 'message' && parsed.answer) {
                                        fullResponse += parsed.answer;
                                        updateStreamMessage(messageId, fullResponse);
                                    } else if (parsed.event === 'message_end') {
                                        if (parsed.conversation_id) {
                                            conversationId = parsed.conversation_id;
                                            updateConversationId(conversationId);
                                        }
                                        finalizeStreamMessage(messageId, fullResponse, parsed.metadata);
                                        break;
                                    } else if (parsed.event === 'error') {
                                        throw new Error(parsed.error || '流式响应错误');
                                    }
                                } catch (e) {
                                    console.warn('解析流式数据失败:', data, e);
                                    // 如果不是JSON格式，可能是纯文本内容
                                    if (data.trim() && !data.startsWith('{')) {
                                        fullResponse += data;
                                        updateStreamMessage(messageId, fullResponse);
                                    }
                                }
                            }
                        } else if (line.trim() && !line.startsWith('event:') && !line.startsWith('id:')) {
                            // 处理非SSE格式的纯文本流
                            try {
                                const parsed = JSON.parse(line);
                                if (parsed.event === 'message' && parsed.answer) {
                                    fullResponse += parsed.answer;
                                    updateStreamMessage(messageId, fullResponse);
                                } else if (parsed.event === 'message_end') {
                                    if (parsed.conversation_id) {
                                        conversationId = parsed.conversation_id;
                                        updateConversationId(conversationId);
                                    }
                                    finalizeStreamMessage(messageId, fullResponse, parsed.metadata);
                                    break;
                                }
                            } catch (e) {
                                // 如果不是JSON，可能是纯文本
                                if (line.trim() !== 'end' && !line.includes('message_end')) {
                                    fullResponse += line;
                                    updateStreamMessage(messageId, fullResponse);
                                }
                            }
                        }
                    }
                }
                
                updateStatus('就绪');
            } catch (error) {
                console.error('流式请求失败:', error);
                addErrorMessage('流式响应失败: ' + error.message);
                updateStatus('错误');
                const failedMessage = document.getElementById(messageId);
                if (failedMessage) {
                    failedMessage.remove();
                }
            } finally {
                setLoading(false);
                document.getElementById('streamingIndicator').style.display = 'none';
            }
        }
        
        function addMessage(content, type, metadata) {
            const messagesContainer = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + type;
            
            let infoText = '';
            if (metadata) {
                const time = new Date(metadata.createdAt || Date.now()).toLocaleTimeString();
                const tokens = metadata.totalTokens ? metadata.totalTokens + ' tokens' : '';
                const latency = metadata.latency ? metadata.latency.toFixed(2) + 's' : '';
                infoText = (time + ' ' + tokens + ' ' + latency).trim();
            } else if (type === 'user') {
                infoText = new Date().toLocaleTimeString();
            }
            
            messageDiv.innerHTML = '<div class="message-content">' + content + (infoText ? '<div class="message-info">' + infoText + '</div>' : '') + '</div>';
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        
        function addErrorMessage(message) {
            const messagesContainer = document.getElementById('chatMessages');
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error';
            errorDiv.textContent = '❌ ' + message;
            messagesContainer.appendChild(errorDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        
        function setLoading(isLoading) {
            const loading = document.getElementById('loading');
            const sendButton = document.getElementById('sendButton');
            
            loading.style.display = isLoading ? 'block' : 'none';
            sendButton.disabled = isLoading;
            sendButton.textContent = isLoading ? '发送中...' : '发送';
        }
        
        function updateStatus(status) {
            document.getElementById('status').textContent = status;
        }
        
        function updateConversationId(id) {
            document.getElementById('conversationId').textContent = '会话ID: ' + id.substring(0, 8) + '...';
        }
        
        function updateStreamMessage(messageId, content) {
            const messageElement = document.getElementById(messageId);
            if (messageElement) {
                const contentElement = messageElement.querySelector('.stream-content');
                if (contentElement) {
                    contentElement.textContent = content;
                }
                const messagesContainer = document.getElementById('chatMessages');
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }
        }
        
        function finalizeStreamMessage(messageId, content, metadata) {
            const messageElement = document.getElementById(messageId);
            if (messageElement) {
                const time = new Date().toLocaleTimeString();
                const tokens = metadata && metadata.usage ? metadata.usage.total_tokens + ' tokens' : '';
                const latency = metadata && metadata.usage ? metadata.usage.latency.toFixed(2) + 's' : '';
                const infoText = (time + ' ' + tokens + ' ' + latency).trim();
                
                messageElement.innerHTML = '<div class="message-content">' + content + '<div class="message-info">' + infoText + '</div></div>';
            }
        }
        
        function setMode(mode) {
            currentMode = mode;
            
            document.querySelectorAll('.mode-btn').forEach(function(btn) {
                btn.classList.remove('active');
            });
            document.getElementById(mode + 'Btn').classList.add('active');
            
            if (currentEventSource) {
                currentEventSource.close();
                currentEventSource = null;
            }
            
            updateStatus('模式切换: ' + getModeText(mode));
        }
        
        function getModeText(mode) {
            switch (mode) {
                case 'sync': return '同步模式';
                case 'async': return '异步模式';
                case 'stream': return '流式模式';
                default: return '未知模式';
            }
        }
        
        async function checkHealth() {
            try {
                const response = await fetch(apiBase + '/health');
                const result = await response.json();
                if (result.success) {
                    updateStatus('服务正常');
                } else {
                    updateStatus('服务异常');
                }
            } catch (error) {
                updateStatus('服务不可用');
            }
        }
        
        checkHealth();
    </script>
</body>
</html>